package com.bazaaroid.server.gae.core.dao.partner.impl;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import au.com.bytecode.opencsv.CSVReader;

import com.bazaaroid.server.gae.core.dao.impl.JDOGenericDAOImpl;
import com.bazaaroid.server.gae.core.dao.partner.CategoryDAO;
import com.bazaaroid.server.gae.core.persistence.model.partner.Category;
import com.google.appengine.api.datastore.Key;

public class JDOCategoryDAOImpl extends JDOGenericDAOImpl<Category, Key>
		implements CategoryDAO {

	public Category getCategoryByName(String name) {
		PersistenceManager persistenceManager = getPersistenceManager();
		persistenceManager.setDetachAllOnCommit(true);
		Category category = null;

		Query query = persistenceManager.newQuery(getEntityClass());
		query.setFilter("name == nameParam");
		query.declareParameters("String nameParam");
		query.setUnique(true);

		try {
			category = (Category) query.execute(name);
		}
		finally {
			query.closeAll();
			persistenceManager.close();
		}

		return category;
	}

	@Override
	public void importCategoriesFromFile(String filePath) {
		CSVReader csvReader = null;

		Map<String, Category> categories = new HashMap<String, Category>();
		for(Category c: getAll())
			categories.put(c.getName(), c);

		try {
			InputStreamReader inputStreamReader = new InputStreamReader(
					new BufferedInputStream(new FileInputStream(filePath)), "UTF-8");

			csvReader = new CSVReader(inputStreamReader, ';', '\"', 1);

			Date today = new Date();
			String [] nextLine;

			while ((nextLine = csvReader.readNext()) != null) {
				String name = nextLine[0].trim();

				Category category = categories.containsKey(name)
					? categories.get(name)
					: null;

				if(category == null) {
					category = new Category();
					category.setName(name);
					category.setCreated(today);
			   	}
				else
					categories.remove(name);

				category.setModified(today);
				makePersistent(category);
			}

			csvReader.close();

			if(!categories.isEmpty()) {
				Set<Key> categoryKeys = new HashSet<Key>();
				for(String categoryName: categories.keySet())
					categoryKeys.add(categories.get(categoryName).getKey());

				deleteAll(categoryKeys);
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}

}
